package com.bytedance.frameworks.baselib.network.dispatcher;

import android.os.Process;
import android.text.TextUtils;

import com.bytedance.common.utility.Logger;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;

class ApiDispatcher extends Thread {
    private static AtomicInteger sWorkingThreadCount = new AtomicInteger();
    private final BlockingQueue mBlockingQueue;
    private volatile boolean isInterrupted;
    private String mTag = "ApiDispatcher";

    public ApiDispatcher(BlockingQueue blockingQueue, String name, String tag) {
        super(TextUtils.isEmpty(name) ? "ApiDispatcher-Thread" : name);
        this.isInterrupted = false;
        this.mBlockingQueue = blockingQueue;
        this.mTag = tag;
    }

    public void release() {
        this.isInterrupted = true;
        this.interrupt();
    }

    public void run() {
        String v0_3;
        String v1;
        String v2;
        Object v0_1;
        Process.setThreadPriority(10);
        do {
            try {
                v0_1 = this.mBlockingQueue.take();
            } catch (InterruptedException e) {
                if (!this.isInterrupted) {
                    continue;
                } else {
                    return;
                }
            }
            if (v0_1 == null) {
                continue;
            }

            if (!(v0_1 instanceof AbsRequest)) {
                continue;
            }

            if (((AbsRequest) v0_1).isCanceled()) {
                continue;
            }

            v2 = Thread.currentThread().getName();
            v1 = ((AbsRequest) v0_1).getName();
            if (!android.support.design.a.isTextEmpty(v1) && !android.support.design.a.isTextEmpty(v2)) {
                Thread.currentThread().setName(v1);
            }

            Logger.d(this.mTag, "thread (inc) count: " + sWorkingThreadCount.incrementAndGet());
            try {
                ((AbsRequest) v0_1).run();
            } catch (Exception e) {
                Logger.e(this.mTag, "Unhandled exception: " + e);
            }
            v0_3 = v1;
            v1 = v2;
            if (!android.support.design.a.isTextEmpty(v0_3) && !android.support.design.a.isTextEmpty(v1)) {
                Thread.currentThread().setName(v1);
            }

            Logger.d(this.mTag, "thread (dec) count: " + sWorkingThreadCount.decrementAndGet());
            continue;
        } while (true);
    }
}

